package com.example.service.impl;

import com.example.dao.ManagerDao;
import com.example.entity.Manager;
import com.example.service.ManagerService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author fyx
 */
@Service
public class ManagerServiceImpl implements ManagerService {
    @Resource
    private ManagerDao mapper;

    @Override
    @Cacheable("managerInfo")
    public Manager findManagerById(int id) {
        return mapper.findManagerById(id);
    }

    @Override
    public boolean addManager(Manager manager) {
        String username = manager.getAccount();
        if (mapper.findOneByAccount(username) != null) {
            return false;
        }
        SimpleHash hash = new SimpleHash("MD5", manager.getPassword(), username + "simpleWoNiu");
        manager.setPassword(hash.toHex());
        mapper.addManager(manager);
        return true;
    }

    @Override
    public boolean deleteManager(int id) {
        return mapper.deleteById(id) != 0;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean updateManager(Manager manager) {
        if (mapper.findManagerById(manager.getId()) != null) {
            mapper.updateManager(manager);
            return true;
        }
        return false;
    }

    @Override
    public List<Manager> findAll() {
        return mapper.findAll();
    }
}
